package com.yehuishou.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.yehuishou.pojo.HUser;
/**
 * 后台登录
 * @author zxb
 *
 */

@Controller
public class LoginController {
	
	@RequestMapping("/")
	public String index() {
		return "login";
	}
	
	//登录功能
	@RequestMapping("/index")
	public String login(HUser huser , Model model ) {
		// 基于shiro实现登录
		Subject subject = SecurityUtils.getSubject();
		
		/*if(hus==null) {
			//判断用户登录没有
			Collection<Session> sessions = sessionDAO.getActiveSessions();
			if(sessions != null && sessions.size()>0){
				for (Session session : sessions) {
					HUser hu = (HUser) session.getAttribute("huser");
					if(hu != null && hu.getUname().equals(huser.getUname())) {
						model.addAttribute("msg", "用户已经登录");
						return "login";
					}
				}
			}
		}*/
		// 用户名和密码信息
		AuthenticationToken token = new UsernamePasswordToken(
				huser.getUname(), huser.getUpassword());
		try {
			subject.login(token);
			// 登录成功
			// 将用户信息 保存到 Session
			HUser huser1 = (HUser) subject.getPrincipal();
			subject.getSession().setAttribute("huser", huser1);
			return "index";
		} catch (Exception e) {
			//登录失败
			model.addAttribute("msg", "用户或密码错误");
			return "login";
		}
	}
	
	//退出登录
	@RequestMapping("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	
	
}
